package com.xaicode.learn.netty.tcpProtocol;

import cn.hutool.core.util.RandomUtil;
import com.google.common.base.Strings;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;

import static java.nio.charset.StandardCharsets.*;

/**
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/20 0020 9:58
 */
@Slf4j
public class NettyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private final AtomicInteger count = new AtomicInteger(0);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {

        if (count.get() == 0) {
            log.info("\r\n" + Strings.repeat("-", 20));
        }

        // receive client message
        Integer len = msg.getLen();
        byte[] content = msg.getContent();
        log.info("receive count [{}] msg: len={}, content={}",
                count.incrementAndGet(),
                len,
                new String(content, UTF_8));

        // reply
        byte[] replyContent = RandomUtil.randomString(RandomUtil.randomInt(5, 10)).getBytes(UTF_8);
        int replyLength = replyContent.length;
        MessageProtocol replyMessage = MessageProtocol.builder()
                .len(replyLength)
                .content(replyContent)
                .build();
        log.info("reply client [{}] msg: {}", ctx.channel().remoteAddress(), replyMessage);
        ctx.writeAndFlush(replyMessage);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
